<template>
	<view>
		<view class="gl-header">
			<view class="gl-header-left" style="flex-wrap: wrap;">
				<uni-search-bar v-model="search" placeholder="关键字搜索" cancelButton="none"
					@confirm="searchChange"></uni-search-bar>
				<uni-data-select v-model="curState" :localdata="stateArray" emptyTips="没有" label="选择订单状态"
					placeholder="所有订单" style="width: 300px;" @change="curStateChange"></uni-data-select>
				<uni-datetime-picker type="daterange" v-model="range" @click="curRangeChange" />
				<view class="gl-button gl-button-base" hover-class="button-base-hover" :hover-stay-time="100"
					@click="fastDateChange('today')">
					<uni-icons type="calendar" size="18" color="#fff"></uni-icons>
					<text style="font-size: small;">今天</text>
				</view>
				<view class="gl-button gl-button-base" hover-class="button-base-hover" :hover-stay-time="100"
					@click="fastDateChange('lastday')">
					<uni-icons type="calendar" size="18" color="#fff"></uni-icons>
					<text style="font-size: small;">昨天</text>
				</view>
				<view class="gl-button gl-button-base" hover-class="button-base-hover" :hover-stay-time="100"
					@click="fastDateChange('week')">
					<uni-icons type="calendar" size="18" color="#fff"></uni-icons>
					<text style="font-size: small;">本周</text>
				</view>
				<view class="gl-button gl-button-base" hover-class="button-base-hover" :hover-stay-time="100"
					@click="fastDateChange('moon')">
					<uni-icons type="calendar" size="18" color="#fff"></uni-icons>
					<text style="font-size: small;">本月</text>
				</view>
				<view class=""></view>
			</view>
			<view class="gl-header-right">
				<view class="gl-button gl-button-base" hover-class="button-base-hover" :hover-stay-time="100"
					@click="refresh">
					<uni-icons type="reload" size="18" color="#fff"></uni-icons>
					<text style="font-size: small;">刷新</text>
				</view>
			</view>
		</view>


		<view class="gl-body table-container" :style="{height:swiperH+'px'}">
			<uni-table type="selection" emptyText="暂无更多数据">
				<uni-tr class="table-head">
					<uni-th align="center" width="30">ID</uni-th>
					<uni-th>单号</uni-th>
					<uni-th>类型</uni-th>
					<uni-th>订单金额</uni-th>
					<uni-th>代金券</uni-th>
					<uni-th>应付金额</uni-th>
					<uni-th>实付金额</uni-th>
					<uni-th>支付方式</uni-th>
					<uni-th>状态</uni-th>
					<uni-th>结算</uni-th>
					<uni-th>退单</uni-th>
					<uni-th>用户</uni-th>
					<uni-th>下单时间</uni-th>
					<uni-th>最近更新</uni-th>
					<uni-th>
						<view style="display: flex;align-items: center;gap: 10px;">
							<view class="gl-link gl-link-base" @click="refresh">刷新</view>
							<view class="gl-link gl-link-base" @click="exportXlsx">导出</view>
							<!--view class="gl-link gl-link-base">打印</view-->
						</view>
					</uni-th>
				</uni-tr>
				<uni-tr v-for="(item,index) in orderArray" :key="index">
					<uni-td>{{item.id}}</uni-td>
					<uni-td> <text @click="navInfoEvent(item.id)">{{item.reqsn}}</text></uni-td>
					<uni-td>{{item.mode}}</uni-td>
					<uni-td style="color: #dd524d">￥{{(item.aprice / 100).toFixed(2)}}</uni-td>
					<uni-td>{{calaCard(item.order_card)}}</uni-td>
					<uni-td style="color: #007aff">￥{{(item.pprice / 100).toFixed(2)}}</uni-td>
					<uni-td style="color: #4cd964">￥{{(calaWxpay(item.order_pay) / 100).toFixed(2)}}</uni-td>
					<uni-td>{{item.payment}}</uni-td>
					<uni-td :style="{color: zipState(item.status).color}">{{zipState(item.status).name}}</uni-td>
					<uni-td style="color: #f0ad4e;">{{Boolean(item.is_foot)?'已结算':''}}</uni-td>
					<uni-td>{{Boolean(item.repay) || ''}}</uni-td>
					<uni-td>{{item.order_staff.id +' '+item.order_staff.nicename}}</uni-td>
					<uni-td>{{item.created}}</uni-td>
					<uni-td>{{item.lasttime || ''}}</uni-td>
					<uni-td>
						<view class="" style="display: flex;align-items: center;gap: 10px;">
							<text class="gl-link gl-link-base" @click="navInfoEvent(item.id)">详情</text>							
							<text v-if="item.status === 1" class="gl-link gl-link-success" @click="sendEvent(item)">发货</text>							
							<text v-if="item.status === 1" class="gl-link gl-link-error"
								@click="syncEvent(item.reqsn)">派单</text>
							<text v-if="item.status === 2 && isOutDate(item.lasttime)" class="gl-link gl-link-other"
								@click="signEvent(item.reqsn)">签收</text>
							<text v-if="item.status >=1 && item.is_foot != 1" class="gl-link gl-link-warning"
								@click="adviceEvent(item.reqsn)">结算</text>
							<!--	
							<text v-if="item.status < 1" class="gl-link gl-link-error"
								@click="removeEvent(item.id)">移除</text>
							-->
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
		</view>
		<view class="gl-footer">
			<uni-pagination :show-icon="true" :total="count" :pageSize="size" v-model="page" title="翻页"
				@change="curPageChange" />
		</view>
		<!-- 模态弹窗 -->
		<popCarryCardVue ref="popCarry" @accept="refresh"></popCarryCardVue>
	</view>
</template>

<script>
	import psLib from '@/common/psLib';
	import psMethod from '@/common/psMethod';
	import popCarryCardVue from './pop-carry-card.vue';
	import * as XLSX from 'xlsx'; // pnp install xlsx
	export default {
		data() {
			return {
				swiperH: 0,
				sConf: getApp().globalData,
				count: 0, // 记录数
				size: 50, // 页大小
				page: 1, // 当前页					
				search: '',
				range: [], // 选择日期列表							
				orderArray: [], // 订单列表
				curState: -1, // 当前选择状态
				stateArray: [], //所有状态

			}
		},
		mounted() {
			console.log('页面挂载');
			let window = uni.getWindowInfo();
			this.designLayout(window.windowHeight);

			let tmpData = [{
				value: -1,
				text: '所有订单'
			}]
			psLib.allState().forEach(item => {
				tmpData.push({
					value: item.status,
					text: item.name
				})
			})
			this.stateArray = tmpData

			// this.range = [this.today, this.today]
			this.loadDefData()
		},
		props: {
			today: {
				type: String,
				default: () => psLib.hasToday()
			}
		},
		components: {
			popCarryCardVue
		},
		methods: {
			exportXlsx() {
				// 数据
				let dataList = this.orderArray
				let sheet = []
				// 表头
				let title = ['订单号', '类型', '订单金额', '支付金额', '支付方式', '代金券', '状态', '结算', '用户', '下单时间']
				sheet.push(title)

				// 从源数组循环提取需要的字段追加到新数组
				dataList.forEach(item => {
					let rowcontent = []
					rowcontent.push(item.reqsn)
					rowcontent.push(item.ditch)
					rowcontent.push((item.aprice / 100).toFixed(2))
					rowcontent.push((item.pprice / 100).toFixed(2))
					rowcontent.push(item.payment)
					rowcontent.push(this.calaCard(item.order_card))
					rowcontent.push(this.zipState(item.status).name)
					rowcontent.push(Boolean(item.is_foot) ? '已结算' : '')
					rowcontent.push(item.order_staff.id + ' ' + item.order_staff.nicename)
					rowcontent.push(item.created)
					sheet.push(rowcontent)
				})

				// 创建工作簿
				var workbook = XLSX.utils.book_new();

				// 创建工作表
				var worksheet = XLSX.utils.aoa_to_sheet(sheet);

				// 将工作表添加到工作簿
				XLSX.utils.book_append_sheet(workbook, worksheet, "导出信息");

				// H5导出
				XLSX.writeFile(workbook, '导出订单.xlsx');

			},
			calaCard(e) {
				if (!e) {
					return null
				}
				return '-' + (e.value / 100).toFixed(2)
			},
			calaWxpay(e) {
				let m = 0;
				e.forEach(item => {
					if (item.trade_state === 'SUCCESS') {
						m += item.amount_total
					}
				})
				return m
			},
			designLayout(wh) {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.gl-body').boundingClientRect();
					query.select('.gl-footer').boundingClientRect();
					query.exec((res) => {
						this.swiperH = wh - Math.ceil(res[0].top) - Math.ceil(res[1].height) - 10;
					});
				})
			},
			loadDefData() {
				this.refresh()
			},
			zipState(e) {
				return psLib.hasState(e)
			},
			/**
			 * 订单是否超时
			 */
			isOutDate(e) {
				let stamp = Date.now();
				let curTime = Date.parse(e);
				return (stamp - curTime) > 1000 * 3600 * 24 * 10 ? true : false
			},
			fastDateChange(e) {
				if (e === 'today') {
					let day = psLib.hasToday()
					this.range = [day, day]
				}
				if (e === "lastday") {
					let day = psLib.hasLastDay()
					this.range = [day, day]
				}
				if (e === 'week') {
					this.range = psLib.hasWeekDay()
				}
				if (e === 'moon') {
					this.range = psLib.hasMonthDay()
				}
				this.page = 1
				this.$nextTick(() => {
					this.loadOrderList()
				})
			},
			curRangeChange(e) {
				console.log('curRangeChange', this.range);
				this.page = 1
				this.$nextTick(() => {
					this.loadOrderList()
				})
			},
			searchChange(e) {
				console.log('searchChange', e.value);
				this.page = 1
				this.$nextTick(() => {
					this.loadOrderList()
				})
			},
			curStateChange(e) {
				console.log('curStateChange', e);
				this.page = 1
				this.$nextTick(() => {
					this.loadOrderList()
				})
			},
			curPageChange(e) {
				console.log('curPageChange', e.current);
				this.$nextTick(() => {
					this.loadOrderList()
				})
			},
			navInfoEvent(e) {
				console.log('navInfoEvent', e);
				this.$emit('navEvent', e)
			},
			sendEvent(e) {
				console.log('sendEvent', e);
				this.$refs.popCarry.open(e)
			},
			syncEvent(e) {
				let that = this
				uni.showModal({
					title: '提交订单',
					content: '用户下单支付成功后，系统自动提交订单到供应链商户。是否需要手动分配订单',
					success: res => {
						if (res.confirm) {
							// that.loadReqsnAdvice(e)
							let host = that.sConf.host + '/admin/subOrder/';
							let token = that.sConf.auth.token || '';
							let data = {
								reqsn: e
							}
							psMethod.authenticatorPostSync(host, token, data).then(res => {
								console.log('提交订单', res);
								uni.showToast({
									title: '提交完成'
								})
							}).catch(err => {
								console.log('提交订单', err);
								uni.showToast({
									title: '执行失败'
								})
							})
						}
					}
				});
			},
			adviceEvent(e) {
				console.log('adviceEvent', e);
				let that = this
				uni.showModal({
					title: '结算',
					content: '用户下单支付成功后，系统自动结算。是否需要立即结算该订单',
					success: res => {
						if (res.confirm) {
							that.loadReqsnAdvice(e)
						}
					}
				});
			},
			signEvent(e) {
				console.log('signEvent', e);
				let that = this
				uni.showModal({
					title: '签收',
					content: '如用户未主动确认收货，则将于订单发货后的第10天，系统自动确认收货。是否需要手动签收该订单',
					success: res => {
						if (res.confirm) {
							that.loadReqsnSignOut(e)
						}
					}
				})
			},
			removeEvent(e) {
				console.log('removeEvent', e);
				let that = this
				uni.showModal({
					title: '移除',
					content: '用户下单支付超时后，系统自动清理无效订单。是否需要立即移除该订单',
					success: res => {
						if (res.confirm) {
							that.loadReqsnDelete(e)
						}
					}
				});
			},
			refresh() {
				this.search = ''
				this.curState = -1
				this.page = 1
				this.range = []
				this.loadOrderList()
			},
			loadReqsnDelete(e) {
				let host = this.sConf.host + '/admin/orderList/' + e + '/';
				let token = this.sConf.auth.token || '';
				psMethod.authenticatorDeleteSync(host, token).then(res => {
					this.refresh()
				})
			},
			loadReqsnSignOut(e) {
				let host = this.sConf.host + '/admin/signOut/';
				let token = this.sConf.auth.token || '';
				let data = {
					reqsn: e
				}
				psMethod.authenticatorPostSync(host, token, data).then(res => {
					console.log('手动签收', res);
					uni.showToast({
						title: '提交完成'
					})
				}).catch(err => {
					console.log('手动签收', err);
					uni.showToast({
						title: '执行失败'
					})
				})
			},
			loadReqsnAdvice(e) {
				let host = this.sConf.host + '/admin/advice/';
				let token = this.sConf.auth.token || '';
				let data = {
					reqsn: e
				}
				psMethod.authenticatorPostSync(host, token, data).then(res => {
					console.log('立即结算', res);
					uni.showToast({
						title: '提交完成'
					})
				}).catch(err => {
					console.log('立即结算', err);
					uni.showToast({
						title: '执行失败'
					})
				})
			},
			async loadOrderList() {
				console.log('refresh');
				let host = this.sConf.host + '/admin/orderList/';
				let token = this.sConf.auth.token || '';
				let data = {
					page: this.page,
					size: this.size,
					ordering: '-id'
				}
				if (this.search.length > 0) {
					data.search = this.search
				}
				if (this.curState > -1) {
					data.status = this.curState
				}
				if (this.range.length > 0) {
					data.start = this.range[0] + ' 00:00:00'
					data.over = this.range[1] + ' 23:59:59'
				}
				await psMethod.authenticatorGetSync(host, token, data).then(res => {
					console.log('加载订单列表', res);
					this.orderArray = res.resmsg
					this.count = res.count
					this.size = res.size
				}).catch(err => {
					console.log('加载订单失败', err);
					if (err.rescode === 404) {
						this.page--
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.gl-input-radio {
		transform: scale(0.7);
	}

	/* 表格垂直滚动 */
	.table-container {
		/* height: 400px; */
		overflow-y: auto;

		::v-deep .uni-table .table-head th {
			font-weight: bold;
			z-index: 2;
			background-color: #fff;
			position: -webkit-sticky;
			position: sticky;
			top: 0;
		}

		::v-deep .uni-table-scroll {
			overflow: visible;
		}
	}
</style>